package com.sc.search.Dao;

import com.sc.common.pojo.SearchItem;
import com.sc.common.pojo.SearchResult;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @auther sc
 * @Date 2017/10/26
 */
@Repository
public class SearchDaoImpl implements SearchDao {

    @Autowired
    private SolrServer solrServer;

    public SearchResult search(SolrQuery solrQuery) throws SolrServerException {
        QueryResponse response = solrServer.query(solrQuery);
        List<SearchItem> searchItemList = new ArrayList<SearchItem>();
        //取查询结果列表
        SolrDocumentList results = response.getResults();
        for(SolrDocument doc:results ){
            SearchItem item = new SearchItem();
            item.setId(doc.get("id").toString());
            item.setImage(doc.get("item_image").toString());
            item.setPrice(Long.parseLong(doc.get("item_price").toString()));

            item.setSell_point(doc.get("item_sell_point").toString());
            Map<String, Map<String, List<String>>> highlighting = response.getHighlighting();
            List<String> list = highlighting.get(doc.get("id")).get("item_title");
            String itemTitle = "";

            if(list!=null&&list.size()>0){
                itemTitle  = list.get(0);
            }else{
                itemTitle = doc.get("item_title").toString();
            }
            item.setTitle(itemTitle);
            searchItemList.add(item);
        }
        SearchResult result = new SearchResult();
        result.setSearchItemList(searchItemList);
        result.setRecordCount(results.getNumFound());

        return result;
    }
}
